package com.wnhz.work.jy.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.OrderHasAdapter;
import com.wnhz.work.jy.bean.GenerateOrderBean;
import com.wnhz.work.jy.bean.HomeFragment1.RecommendBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * ---生成订单
 */
public class GenerateOrderActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "GenerateOrderActivity";
    private static final int SELECT_GOOD = 5421;
    private TextView title;
    private TextView tv_save, tv_get;
    private ListView listView;
    private OrderHasAdapter mAdapter;

    private ArrayList<RecommendBean> orderList = new ArrayList<>();
    private TextView tv_all_price;

    private EditText et_content;
    private EditText bank_serial_ed;
    private String content;
    private String bank_serial;

    private GenerateOrderBean generateOrderBean;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mAdapter.notifyDataSetChanged();
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generate_order);

        initView();
        bank_serial_ed.requestFocus();
    }


    private void initView() {
        bank_serial_ed = (EditText) findViewById(R.id.bank_serial_ed);//银行流水
        et_content = (EditText) findViewById(R.id.et_content);//备注
        tv_all_price = (TextView) findViewById(R.id.tv_all_price);
        title = (TextView) findViewById(R.id.view_main_middle_title);

        title.setText("订单生成");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.rl_add_goods).setOnClickListener(this);//添加
        findViewById(R.id.tv_true).setOnClickListener(this);

        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_get = (TextView) findViewById(R.id.tv_get);

        tv_save.setOnClickListener(this);//存入
        tv_get.setOnClickListener(this);//取出

        listView = (ListView) findViewById(R.id.view_add_listview);

        mAdapter = new OrderHasAdapter(GenerateOrderActivity.this, orderList, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int index;
                switch (v.getId()) {

                    //删除
                    case R.id.iv_delete:
                        index = (Integer) v.getTag();
                        new AlertDialog.Builder(GenerateOrderActivity.this).setTitle("")//设置对话框标题
                                .setMessage("你确定删除该商品吗？")//设置显示的内容
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        orderList.remove(index);

                                        /*if (shopList.size() == 0) {
                                            mAdapter.setEdit(true);
                                            right.setText("完成");
                                            tv_true.setBackgroundColor(0xffd9d9d9);
                                            onHas();
                                        }*/
                                        mHandler.sendEmptyMessage(1);

                                    }
                                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
                        break;

                    //增加
                    case R.id.tv_add:
                        index = (Integer) v.getTag();
                        int numAdd = orderList.get(index).getmYNum();
                        System.out.println(numAdd + "numAdd");
                        orderList.get(index).setmYNum((numAdd + 1));
                        break;

                    //减少
                    case R.id.tv_minus:
                        index = (Integer) v.getTag();
                        int numSub = orderList.get(index).getmYNum();
                        if (numSub == 1) {
                            MyToast("再减就没了");
                        } else {
                            orderList.get(index).setmYNum(numSub - 1);
                            //orderList.get(index).setGoodNum((numSub - 1) + "");
                        }
                        break;
                }
                setAllMoney();
                mHandler.sendEmptyMessage(1);
            }
        });

        listView.setAdapter(mAdapter);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //存入金库
            case R.id.tv_save:
                tv_save.setBackgroundResource(R.drawable.shap_btn_main_color);
                tv_save.setTextColor(0xffe2bb0a);
                tv_get.setBackgroundResource(R.drawable.butten_white);
                tv_get.setTextColor(0xff333333);
                break;

            //直接取走
            case R.id.tv_get:
                tv_save.setBackgroundResource(R.drawable.butten_white);
                tv_save.setTextColor(0xff333333);
                tv_get.setBackgroundResource(R.drawable.shap_btn_main_color);
                tv_get.setTextColor(0xffe2bb0a);
                break;

            //添加产品
            case R.id.rl_add_goods:
                startActivityForResult((new Intent(this, SelectGoodActivity.class)), SELECT_GOOD);
                break;

            //确定
            case R.id.tv_true:
                ArrayList<RecommendBean> orderList2 = new ArrayList<>();
                bank_serial = bank_serial_ed.getText().toString();
                content = et_content.getText().toString();

                /*else {
                    ewmOrder(orderList2);
                }*/
                for (int i = 0; i < orderList.size(); i++) {
                    if (orderList.get(i).getmYNum() != 0) {
                        orderList2.add(orderList.get(i));
                    }
                }
                if (orderList2.size() == 0) {
                    MyToast("请选择商品");
                } else if (bank_serial == null || "".equals(bank_serial)) {
                    MyToast("请输入银行流水号");
                } else {
                    startActivity(new Intent(getApplication(), SetOrderMsg.class).putExtra("arrayList", orderList2).
                            putExtra("bank_serial_no", bank_serial).putExtra("content", content));
                }

                break;

            default:
                break;
        }
        mHandler.sendEmptyMessage(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SELECT_GOOD) {
            if (resultCode == RESULT_OK) {
                ArrayList<RecommendBean> orderList2 = new ArrayList<>();

                orderList2.clear();
                orderList2 = (ArrayList<RecommendBean>) data.getSerializableExtra("arrayList");
                for (int i = 0; i < orderList2.size(); i++) {
                    RecommendBean bean1 = orderList2.get(i);
                    for (int i1 = 0; i1 < orderList.size(); i1++) {
                        if (bean1.getGoodId().equals(orderList.get(i1).getGoodId())) {
                            orderList.get(i1).setmYNum(orderList2.get(i).getmYNum());
                            orderList2.remove(i);
                            continue;
                        }
                    }
                }
                orderList.addAll(orderList2);
                mAdapter.notifyDataSetChanged();
                setAllMoney();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setAllMoney() {
        double allmoney = 0;
        for (int i = 0; i < orderList.size(); i++) {
            allmoney += Double.parseDouble(orderList.get(i).getGoodPrice()) * orderList.get(i).getmYNum();
        }
        DecimalFormat df = new DecimalFormat("##.##");
        tv_all_price.setText("¥" + df.format(allmoney));
    }

    private void ewmOrder(ArrayList<RecommendBean> orderList) {
        Map<String, Object> map = new HashMap<>();
        //map.put("delivery","0");
        //map.put("truename",truename);
        /*map.put("telephone",telephone);
        map.put("card_no",card_no);
        map.put("certificate_no",certificate_no);*/
        map.put("bank_serial", bank_serial);
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        if (orderList.size() == 0) {
            return;
        }

        double allp = 0;
        for (int i = 0; i < orderList.size(); i++) {
            if (orderList.get(i).getmYNum() != 0) {
                allp += orderList.get(i).getmYNum() * Double.parseDouble(orderList.get(i).getGoodPrice());
                map.put(orderList.get(i).getGoodId(), orderList.get(i).getmYNum() + "");
            }
        }
        if (content != null && !"".equals(content)) {
            map.put("message", content);
        }
        final double finalAllp = allp;
        showDialog();
        XUtil.Post(ConfigUtil.EWMORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    if ("1".equals(re)) {
                        generateOrderBean = new GenerateOrderBean();
                        generateOrderBean = gson.fromJson(result, GenerateOrderBean.class);
                       /* DecimalFormat df = new DecimalFormat("##.##");
                        String qrcode = json.optString("qrcode");
                        String guiyuanOrderid = json.optString("guiyuanOrderid");
                        String pid = json.optString("pid");*/
                        startActivity(new Intent(GenerateOrderActivity.this, OrderCodeActivity.class).putExtra("bean", generateOrderBean));
                    } else {
                        String info = json.optString("info");
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }
}
